package com.hoas.keystore.factory.rsa;

import com.hoas.keystore.factory.aes.AESDecoderFactory;
import com.hoas.keystore.po.MerchantKey;
import com.hoas.keystore.util.RSAUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;


/**
 * @Author: Administrator
 * @Date: 2018/11/6 18:04
 */
public class RSADecoderFactory {

    private static Logger log = LoggerFactory.getLogger(AESDecoderFactory.class);

    public static RSADecoder getServerDecoder(MerchantKey key) {

        if (key == null) {
            return null;
        }

        if ("RSA".equals(key.getKeyType())) {
            try {

                RSADecoder rsa = new RSADecoder(key.getClientPrivateKey(), key.getServerPublicKey());
                rsa.setVersion(key.getKeyVersion());
                rsa.setEncryptText(key.getEncryptText());

                rsa.setMerchantId( key.getMerchantId() );

                return rsa;

            } catch (Exception e) {
                log.error("服务端编码解析器创建异常", e);
            }

        }

        return null;
    }

    public static RSADecoder getClientDecoder(MerchantKey key) {

        if (key == null) {
            return null;
        }

        if ("RSA".equals(key.getKeyType())) {

            try {

                RSADecoder rsa = new RSADecoder(key.getServerPrivateKey(), key.getClientPublicKey());
                rsa.setVersion(key.getKeyVersion());
                rsa.setEncryptText(key.getEncryptText());
                return rsa;

            } catch (Exception e) {
                log.error("客户端编码解析器创建异常", e);
            }

        }

        return null;

    }

    public static void genKeyPairs(MerchantKey key) {

        if (key == null) {
            return;
        }

        if ("RSA".equals(key.getKeyType())) {

            try {

                Map<String,String> keypairs = RSAUtil.gen();

                key.setClientPublicKey( keypairs.get("publicKey") );
                key.setClientPrivateKey( keypairs.get("privateKey") );

                Map<String,String> serverKeypairs = RSAUtil.gen();

                key.setServerPublicKey( serverKeypairs.get("publicKey") );
                key.setServerPrivateKey( serverKeypairs.get("privateKey") );


            } catch (Exception e) {
                log.error("客户端编码解析器创建异常", e);
            }

        }



    }

}
